﻿using Newtonsoft.Json;
using System;
using System.Data;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Collections.Specialized;

namespace EarringsRecommendationWeb
{
    public partial class index : CheckUserSession
    {
        private string[] _Result = new string[2];
        private string _email = string.Empty;
        private string _pointColl;
        private string _earlobePosition = string.Empty;
        private string _REarlobePosition = string.Empty;
        private string _LEarlobePosition = string.Empty;
        private string _faceImage = string.Empty;
        private string _personId = string.Empty;
        private string _cdWidth = string.Empty;
        private string _jawShape = string.Empty;
        private string _hairLine = string.Empty;


        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            Member mem = Session["member"] as Member;

            if (mem != null)
            {
                Response.Write("<input id='hidden-email' type='hidden' value='" + mem.Email + "'>");
                Response.Write("<input id='hidden-name' type='hidden' value='" + mem.Name + "'>");
            }

            if (Session["ImageFile"] != null)
            {
                string previousFile = Session["ImageFile"].ToString();
            }
        }

        protected void NextStep2(object sender, EventArgs e)
        {
            Member mem = Session["member"] as Member;
            if (mem != null)
            {
                _email = mem.Email;
            }

            #region Find Face Shape
            string fileName = string.Empty;
            if (Request["hasFile"] == "true")
            {
                if (Session["ImageFile"] != null)
                {
                    _personId = Session["PersonalId"].ToString();
                }
                else
                {
                    _personId = Guid.NewGuid().ToString();
                }

                fileName = _personId + ".jpg";
                FileUpload.PostedFile.SaveAs(Server.MapPath("~/Upload/") + fileName);

                string processName = Server.MapPath("~/Upload/") + "WatCD.exe";
                string imageFileName = Server.MapPath("~/Upload/") + fileName;
                Session["ImageFile"] = imageFileName;
                Session["PersonalId"] = _personId;

                this.WatCD(fileName);
            }
            else
            {

            }
            #endregion
        }

        public void WatCD(string fileName)
        {
            Process p = new Process();// Process.Start(processName, imageFileName);
            p.StartInfo.WorkingDirectory = Server.MapPath("~/Upload/");
            p.StartInfo.FileName = "WatCD.exe";
            p.StartInfo.Arguments = fileName;
            p.Start();

            p.WaitForExit();
            int width = p.ExitCode;
            //CD Size in Image
            Message.InnerText = width.ToString();
            _cdWidth = width.ToString();

            _faceImage = fileName;

            //File Face Shape
            _Result = this.CalculateFace();

            if (string.IsNullOrEmpty(_Result[1]))
            {
                //string message = "ไม่สามารถคำนวณรูปหน้าได้ กรุณาอีกครั้ง";
                string filePath = "Upload/" + fileName;

                Response.Write("<img id=\"previous-img\" class=\"hidden\" src=\"" + filePath + "\">");
                hasFile.Value = "true";
            }
            else
            {
                //Pass Personal ID to Next Step 
                var values = new NameValueCollection();
                values["personalid"] = _personId;

                //Check record in DB

                bool hasRecord = this.CheckRecord();
                if (!hasRecord)
                {
                    this.SaveMemEarrings();
                }
                else
                {
                    this.UpdateMemEarrings();
                }

                WebExtensions.RedirectWithData(values, "index2.aspx");
            }
        }

        public string[] CalculateFace()
        {
            string[] returnValue = new string[2];

            _pointColl = txtout.InnerText;
            var jarray = JsonConvert.DeserializeObject<List<pointTmp>>(_pointColl);
            Session["PointJSON"] = _pointColl;

            Dictionary<int, Point> pointColl = new Dictionary<int, Point>();

            int i = 0;
            foreach (var p in jarray)
            {
                pointTmp temp = p as pointTmp;
                i = i + 1;
                Point newP = new Point(temp.x, temp.y);
                pointColl.Add(i, newP);
            }

            ShapeManagement shpMgmt = new ShapeManagement(pointColl);
            _earlobePosition = shpMgmt.GetEarlobePosition();
            _REarlobePosition = shpMgmt.GetRightEarlobePosition();
            _LEarlobePosition = shpMgmt.GetLeftEarlobePosition();

            ////หาอัตราส่วน ความกว้าง : ความยาว
            double faceWidth = shpMgmt.FaceWidth;
            double faceLength = shpMgmt.FaceLength;

            #region Find Neck

            double incorrectFaceLenght = faceLength * .05;
            double idealFaceLenght = shpMgmt.NeckLength * 4;

            double diff = Math.Abs(idealFaceLenght - faceLength);
            //คอ 24 x 4 หน้า = 96
            //หน้าจริง 100 5%ของ หน้าจริง = 5
            //diff (96-100) = 4

            //Find Short or Long Neck
            if (idealFaceLenght < faceLength)
            {
                returnValue[0] = "Short";
            }
            else
            {
                returnValue[0] = "Long";
            }

            #endregion

            //Jaw Shape
            _jawShape = Request.Form["rdoJaw"];
            _hairLine = Request.Form["rdoHairline"];

            #region Find FaceShape
            string faceShapeResult = string.Empty;

            double lengthRatio = Math.Round((faceLength / faceWidth), 1);

            #region Comment
            ////กรณี Length < Width
            //if (lengthRatio < 1.5)
            //{
            //    if (_jawShape == JawShape.Pointy.ToString())
            //    {
            //        if (DiamondFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
            //        {
            //            if (string.IsNullOrEmpty(faceShapeResult))
            //            {
            //                faceShapeResult += FaceShape.Diamond.ToString();
            //            }
            //            else
            //            {
            //                faceShapeResult += "," + FaceShape.Diamond.ToString();
            //            }
            //        }
            //    }
            //    else if (_jawShape == JawShape.Round.ToString())
            //    {
            //        if (RoundFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
            //        {
            //            if (string.IsNullOrEmpty(faceShapeResult))
            //            {
            //                faceShapeResult += FaceShape.Round.ToString();
            //            }
            //            else
            //            {
            //                faceShapeResult += "," + FaceShape.Round.ToString();
            //            }
            //        }

            //        if (HeartFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
            //        {
            //            if (string.IsNullOrEmpty(faceShapeResult))
            //            {
            //                faceShapeResult += FaceShape.Heart.ToString();
            //            }
            //            else
            //            {
            //                faceShapeResult += "," + FaceShape.Heart.ToString();
            //            }
            //        }
            //    }
            //    else if (_jawShape == JawShape.Square.ToString())
            //    {
            //        if (SquareFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
            //        {
            //            if (string.IsNullOrEmpty(faceShapeResult))
            //            {
            //                faceShapeResult += FaceShape.Square.ToString();
            //            }
            //            else
            //            {
            //                faceShapeResult += "," + FaceShape.Square.ToString();
            //            }
            //        }
            //    }
            //}
            ////กรณี Length > Width
            //else
            //{
                //if (_jawShape == JawShape.Pointy.ToString())
                //{
                //    if (DiamondFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Diamond.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Diamond.ToString();
                //        }
                //    }
                //    if (InvertedTriangleFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.InvertedTriangle.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.InvertedTriangle.ToString();
                //        }
                //    }
                //}
                //else if (_jawShape == JawShape.Round.ToString())
                //{
                //    if (RoundFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Round.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Round.ToString();
                //        }
                //    }

                //    if (OvalFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Oval.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Oval.ToString();
                //        }
                //    }

                //    if (HeartFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Heart.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Heart.ToString();
                //        }
                //    }

                //    if (OblongFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Oval.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Oval.ToString();
                //        }
                //    }
                //}
                //else if (_jawShape == JawShape.Square.ToString())
                //{
                //    if (SquareFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Square.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Square.ToString();
                //        }
                //    }

                //    if (OblongFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Oval.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Oval.ToString();
                //        }
                //    }

                //    if (PearFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                //    {
                //        if (string.IsNullOrEmpty(faceShapeResult))
                //        {
                //            faceShapeResult += FaceShape.Pear.ToString();
                //        }
                //        else
                //        {
                //            faceShapeResult += "," + FaceShape.Pear.ToString();
                //        }
                //    }
                //}
            //}
            #endregion

            if (_jawShape == JawShape.Pointy.ToString())
            {
                if (DiamondFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Diamond.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Diamond.ToString();
                    }
                }
                if (InvertedTriangleFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.InvertedTriangle.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.InvertedTriangle.ToString();
                    }
                }
            }
            else if (_jawShape == JawShape.Round.ToString())
            {
                if (RoundFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Round.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Round.ToString();
                    }
                }

                if (OvalFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Oval.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Oval.ToString();
                    }
                }

                if (HeartFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Heart.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Heart.ToString();
                    }
                }

                if (OblongFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Oblong.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Oblong.ToString();
                    }
                }
            }
            else if (_jawShape == JawShape.Square.ToString())
            {
                if (SquareFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Square.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Square.ToString();
                    }
                }

                if (OblongFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Oblong.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Oblong.ToString();
                    }
                }

                if (PearFace.CheckFaceShape(faceWidth, faceLength, shpMgmt.Forehead, shpMgmt.Cheekbones, shpMgmt.JawLength, _hairLine))
                {
                    if (string.IsNullOrEmpty(faceShapeResult))
                    {
                        faceShapeResult += FaceShape.Pear.ToString();
                    }
                    else
                    {
                        faceShapeResult += "," + FaceShape.Pear.ToString();
                    }
                }
            }
            returnValue[1] = GlobalFunction.GetFirstFaceShape(faceShapeResult);

            #endregion

            return returnValue;
        }

        public bool CheckRecord()
        {
            bool returnValue = false;

            string sqlStr = "SELECT * FROM MEMEarrings WHERE Email = '" + _email + "' AND Person_ID = '" + _personId + "'";
            DataTable dtResult = new DataTable();
            dtResult = SqlClientUtility.ExecuteDataTable(CommandType.Text, sqlStr);

            if (dtResult.Rows.Count > 0)
            {
                returnValue = true;
            }
            return returnValue;

        }

        public void SaveMemEarrings()
        {
            //Save MemberEarrings
            MemberEarrings memEarrings = new MemberEarrings();
            memEarrings.PersonalId = _personId;
            memEarrings.FaceShape = _Result[1];
            memEarrings.JawlineShape = _jawShape;
            memEarrings.FacePosition = Session["PointJSON"].ToString();
            memEarrings.Neck = _Result[0];
            memEarrings.REarlobePosition = _REarlobePosition;
            memEarrings.LEarlobePosition = _LEarlobePosition;
            memEarrings.CDWidth = _cdWidth;

            GlobalFunction.InsertMemberEarrings(memEarrings, _email);

            Session["PointJSON"] = null;
        }

        public void UpdateMemEarrings()
        {
            //Save MemberEarrings
            MemberEarrings memEarrings = new MemberEarrings();
            memEarrings.PersonalId = _personId;
            memEarrings.FaceShape = _Result[1];
            memEarrings.JawlineShape = _jawShape;
            memEarrings.FacePosition = Session["PointJSON"].ToString();
            memEarrings.Neck = _Result[0];
            memEarrings.REarlobePosition = _REarlobePosition;
            memEarrings.LEarlobePosition = _LEarlobePosition;
            memEarrings.CDWidth = _cdWidth;

            GlobalFunction.UpdateMemberEarrings(memEarrings, _email);

            Session["PointJSON"] = null;
        }

        public class pointTmp
        {
            [JsonProperty(PropertyName = "x")]
            public int x { get; set; }
            [JsonProperty(PropertyName = "y")]
            public int y { get; set; }
        }
    }
}